package server

import (
	"context"
	"gitee.com/smallow/srpc/infrastructure/business"
	"gitee.com/smallow/srpc/infrastructure/conf"
	"gitee.com/smallow/srpc/infrastructure/model"
	"gitee.com/smallow/srpc/infrastructure/proto/pb"
	"github.com/pkg/errors"
	"go.uber.org/zap"
	"log"
)

var (
	LogInfo = "[%s] method: [%s] "
)

const (
	ISUserService          = "UserService"
	MUserServiceCreateUser = "CreateUser"
	MUserServiceFindUser   = "FindUser"
	MUserServiceUpdateUser = "UpdateUser"
	MUserServiceDeleteUser = "DeleteUser"
)

type UserService struct{}

// 创建用户
func (us *UserService) CreateUser(context context.Context, req *pb.CreateUserReq) (*pb.CreateUserResp, error) {
	//conf.Logger().Info(fmt.Sprintf(LogInfo, ISUserService, MUserServiceCreateUser), zap.Any("param:", in))
	if req.AppID == "" {
		return &pb.CreateUserResp{
			Code:    -1,
			Message: "failed",
		}, errors.New("appID为空")
	}
	if business.PhoneExist(req.Phone) {
		return &pb.CreateUserResp{
			Code:    -1,
			Message: "failed",
		}, errors.New("手机号已存在")
	}
	user := &model.Employee{
		Name:         req.Name,
		Phone:        req.Phone,
		CompanyId:    int(req.CompanyID),
		AppId:        req.AppID,
		Memo:         req.Memo,
		DepartmentId: int(req.DepartmentID),
		Sex:          uint8(req.Sex),
		Age:          uint8(req.Age),
		AuthState:    int(req.AuthState),
	}
	user.State = model.UserNormal
	err := business.SaveUser(user)
	if err != nil {
		return &pb.CreateUserResp{
			UserID:  0,
			Code:    -1,
			Message: "failed",
		}, err
	}
	return &pb.CreateUserResp{
		UserID:  int32(user.ID),
		Code:    0,
		Message: "success",
	}, nil
}

// 根据id查找用户信息
func (us *UserService) FindUser(context context.Context, in *pb.FindUserReq) (*pb.FindUserResp, error) {
	if in.UserID == 0 || in.AppID == "" {
		return &pb.FindUserResp{
			Success: false,
			Message: "缺少参数",
		}, errors.New("缺少参数")
	}
	where := &model.Employee{
		BaseModel: model.BaseModel{ID: int(in.UserID), AppID: in.AppID},
	}
	user, err := business.FindUser(where)
	user_ := &pb.User{}
	if err != nil {
		log.Printf("查找用户信息出错：用户id[%d] appid[%s] 错误[%s]", in.UserID, in.AppID, err.Error())
		return &pb.FindUserResp{
			Success: false,
			Message: "查找用户信息出错",
		}, err
	} else {
		user_ = &pb.User{
			Id:           int32(user.ID),
			Name:         user.Name,
			Phone:        user.Phone,
			Sex:          int32(user.Sex),
			Age:          int32(user.Age),
			CompanyID:    int32(user.CompanyId),
			AppID:        user.AppID,
			Memo:         user.Memo,
			DepartmentID: int32(user.DepartmentId),
			CreateAt:     user.CreateAt.String(),
			State:        int32(user.State),
			AuthState:    int32(user.AuthState),
		}
	}

	return &pb.FindUserResp{
		User:    user_,
		Success: true,
	}, nil

}

func (us *UserService) FindUsers(context context.Context, in *pb.FindUsersReq) (*pb.FindUsersResp, error) {
	conf.Logger().Info("userService execute GetUser ", zap.Any("UserQueryReq:", in))
	return nil, nil
}

// 更新用户信息
func (us *UserService) UpdateUser(ctx context.Context, req *pb.UpdateUserReq) (*pb.UpdateUserResp, error) {
	if req.UserID == 0 || req.AppID == "" {
		return &pb.UpdateUserResp{
			Code:    -1,
			Message: "缺少参数",
		}, errors.New("缺少参数")
	}
	// 验证id有效性
	temp, _ := business.FindUser(&model.Employee{BaseModel: model.BaseModel{ID: int(req.UserID)}})
	if temp.ID == 0 {
		return &pb.UpdateUserResp{
			Code:    -1,
			Message: "无效的id",
		}, errors.New("无效的id")
	}
	if req.Phone != "" {
		temp2, _ := business.FindUser(&model.Employee{Phone: req.Phone})
		if temp2 != nil && temp2.ID != int(req.UserID) {
			return &pb.UpdateUserResp{
				Code:    -1,
				Message: "手机号已存在",
			}, errors.New("手机号已存在")
		}
	}
	// 更新
	user := &model.Employee{
		BaseModel:    model.BaseModel{AppID: req.AppID, ID: int(req.UserID)},
		Name:         req.Name,
		Phone:        req.Phone,
		Age:          uint8(req.Age),
		Sex:          uint8(req.Sex),
		DepartmentId: int(req.DepartmentID),
		CompanyId:    int(req.CompanyID),
		State:        int8(req.State),
		AuthState:    int(req.AuthState),
		Memo:         req.Memo,
	}
	err := business.SaveUser(user)
	if err != nil {
		return &pb.UpdateUserResp{
			Code:    -1,
			Message: "failed",
		}, err
	}
	return &pb.UpdateUserResp{
		Code:    0,
		Message: "success",
	}, nil
}

// 删除用户信息
func (us *UserService) DeleteUser(context context.Context, in *pb.UserDelReq) (*pb.UserDelResp, error) {
	if in.UserID == 0 || in.AppID == "" {
		return &pb.UserDelResp{
			Success: false,
			Message: "缺少参数",
		}, errors.New("缺少参数")
	}
	where := &model.Employee{BaseModel: model.BaseModel{ID: int(in.UserID), AppID: in.AppID}}
	existCompany1, _ := business.FindUser(where)
	if existCompany1.ID == 0 {
		return &pb.UserDelResp{
			Success: false,
			Message: "无效的id",
		}, errors.New("无效的id")
	}

	err := business.DeleteUser(where)
	if err != nil {
		return &pb.UserDelResp{
			Success: false,
			Message: "删除失败",
		}, err
	}
	return &pb.UserDelResp{
		Success: true,
	}, nil
}

// 创建用戶账户
func (us *UserService) CreateUA(ctx context.Context, req *pb.CreateUAReq) (*pb.CreateUAResp, error) {
	account := &model.Account{
		BaseModel:     model.BaseModel{AppID: req.AppID},
		BodyID:        int(req.BodyID),
		BodyType:      2, //'账号主体类型1-公司,2-人员,3-部门',
		State:         uint8(req.State),
		BindPhone:     req.BindPhone,
		NickName:      req.NickName,
		AccountNumber: req.AccountNumber,
		Password:      business.GetMd5String(req.Password),
		WxOpenID:      req.WxOpenID,
		AliPayID:      req.AliPayID,
	}
	// 判断账号主体是否已存在账号
	if business.ExistAccount(&model.Account{BodyID: account.BodyID, BodyType: account.BodyType}) {
		log.Printf("创建用戶账户出错：用戶id[%d] appid[%s] 错误[%s]", req.BodyID, req.AppID, "该主体已存在其他账号")
		return &pb.CreateUAResp{Success: false, Message: "该主体已存在其他账号"}, nil
	}
	// 判断账号是否重复
	if business.ExistAccount(&model.Account{AccountNumber: req.AccountNumber}) {
		log.Printf("创建用户账号出错：公司id[%d] appid[%s] 错误[%s]", req.BodyID, req.AppID, "该账号名已存在")
		return &pb.CreateUAResp{Success: false, Message: "该账号名已存在"}, nil
	}
	// 判断手机号是否已存在
	if business.ExistPhone(account.BindPhone) {
		log.Printf("创建用戶账户出错：用戶id[%d] appid[%s] 错误[%s]", req.BodyID, req.AppID, "手机号已绑定其他账号")
		return &pb.CreateUAResp{Success: false, Message: "手机号已绑定其他账号"}, nil
	}
	// 创建   3-员工
	err := business.CreateAccountInfo(account, 3)
	if err == nil {
		return &pb.CreateUAResp{
			Success: true,
			Message: "创建成功",
		}, nil
	} else {
		log.Printf("创建用戶账户出错：用戶id[%d] appid[%s] 错误[%s]", req.BodyID, req.AppID, err.Error())
		return &pb.CreateUAResp{
			Success: false,
			Message: "创建失败",
		}, nil
	}

}
